import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: PostGirl-panent
 * @description: 测试监听文件变化
 * @author: Cheng Zhi
 * @create: 2022-10-04 11:57
 **/
public class LogListenner implements FileAlterationListener {

    Map<String, Long> fileLineRember;

    public LogListenner(Map<String, Long> fileLineRember) {
        this.fileLineRember = fileLineRember;
    }

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
        System.out.println("monitor start scan files..");
    }

    @Override
    public void onDirectoryCreate(File file) {
        String fileName = file.getName();
        System.out.println(fileName + " director created." );
    }

    @Override
    public void onDirectoryChange(File file) {

        String fileName = file.getName();
        System.out.println(fileName + " director created." );
    }

    @Override
    public void onDirectoryDelete(File file) {
        String fileName = file.getName();
        System.out.println(fileName + " director created." );
    }

    @Override
    public void onFileCreate(File file) {
        String fileName = file.getName();
        Long countLines = FileUtils.getFileLineCount(file);
        System.out.println(fileName + "  changed." + "内容总行数为：" + countLines);
        fileLineRember.put(fileName, countLines);
    }

    @Override
    public void onFileChange(File file) {
        String fileName = file.getName();
        Long newLines = FileUtils.getFileLineCount(file);
        long oldLines = 0;
        if (fileLineRember.get(fileName) == null) {
            System.out.println(fileName + "  该文件第一次变更");
        } else {
            oldLines = fileLineRember.get(fileName);
            System.out.println(fileName + "  原文件总行数为：" + oldLines);
        }
        System.out.println(fileName + "  changed." + "变更后内容总行数为：" + newLines);
        fileLineRember.put(fileName, newLines);
        long lines = newLines - oldLines;
        if (lines > 0) {
            String s = FileUtils.readTailContent(file, lines);
            System.out.println(FileUtils.split(s, "POST_GIRL"));
        }

    }

    @Override
    public void onFileDelete(File file) {
        System.out.println(file.getName()+" deleted.");

    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {
        System.out.println("monitor stop scanning..");
    }

}
